package mg.daloji.antandroyd.service;

import java.util.LinkedList;

import mg.daloji.antandroyd.CONSTANTS;
import mg.daloji.antandroyd.Radio;
import mg.daloji.antandroyd.application.App;
import mg.daloji.antandroyd.mediaplayer.IMediaPlayerServiceClient;
import mg.daloji.antandroyd.mediaplayer.StatefulMediaPlayer;
import mg.daloji.antandroyd.mediaplayer.StatefulMediaPlayer.MPStates;
import mg.daloji.antandroyd.mediaplayer.StreamStation;
import mg.daloji.antandroyd.ui.Home;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

public class ServiceSave extends Service  implements OnBufferingUpdateListener, OnInfoListener, OnPreparedListener, OnErrorListener  {
	
	private static final String TAG = ServiceRadio.class.getSimpleName();
	private static final int TIMER_TASK = 0;
	private static final long DELAY = 1000L;
	
	
	public static final String PAUSE_MEDIA_PLAYER = "pause_media_player";
	
	public static final int START_MEDIA_PLAYER = 0;
	
	public static final int STOP_MEDIA_PLAYER = 1;
	
	//public static final String START_MEDIA_PLAYER = "start_media_player";
	
	//public static final String STOP_MEDIA_PLAYER = "stop_media_player";
	
	
	/** Message marker when service is called via its interface. */
	private static final int MESSAGE_INTERFACE = 1;
	
	/** Message marker when service is called via its interface. */
	private static final int MESSAGE_INTENT = 2;
	
	/** Message marker when service is called  with error. */
	private static final int MESSAGE_ERROR = 3;
	
	/** Message marker when service is  finished. */
	private static final int MESSAGE_FINISH = 4;
	
	private StatefulMediaPlayer mMediaPlayer = new StatefulMediaPlayer();

    private IMediaPlayerServiceClient mClient;
    
    private LinkedList<Radio> mlistRadio= new LinkedList<Radio>();
	private Context mContext;
	private Handler mHandler;
		
	private RemoteCallbackList<IServiceRadioCallBack> mObservers = new RemoteCallbackList<IServiceRadioCallBack>();
	
	

	private BroadcastReceiver mBroadcastReceiver =new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			Bundle extra =intent.getExtras();
			if(extra!=null){
				final Message msg = mHandler.obtainMessage();
				msg.what = MESSAGE_INTENT;
				}
				//mHandler.sendMessage(msg);
			}
	};
	
	
	private final IServiceRadio.Stub mMyBindService = new IServiceRadio.Stub() {
		
		public String getString() throws RemoteException {
			Log.d(TAG, "getString called by " + Thread.currentThread().getName());
			return "This string is provided by Service";
		}

		public void setObserver(IServiceRadioCallBack observer)throws RemoteException {
			Log.d(TAG, "setObserver called by " + Thread.currentThread().getName());
			mObservers.register(observer);			
		}
		
		public void removeObserver(IServiceRadioCallBack observer)
				throws RemoteException {
			Log.d(TAG, "removeObserver called by " + Thread.currentThread().getName());
			mObservers.unregister(observer);
		}

		@Override
		public void doPause(IServiceRadioCallBack cb) throws RemoteException {
			// TODO Auto-generated method stub
		
		}

		@Override
		public void doStop(IServiceRadioCallBack cb) throws RemoteException {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void doRelease(IServiceRadioCallBack cb) throws RemoteException {
			// TODO Auto-generated method stub
			
		}
		
		private void sendMessage(int action, String params) {
			Log.i(TAG, "sendMessage: "+action);
			Log.i(TAG, "sendMessage: "+params);
			final Message msg = mHandler.obtainMessage();
			msg.what = MESSAGE_INTERFACE;
			final Bundle msgParams = new Bundle();
			msgParams.putInt("action", action);
			msgParams.putString("params", params);
			msg.obj = MESSAGE_INTERFACE;
			msg.setData(msgParams);
			mHandler.sendMessage(msg);
		}

		@Override
		public void doStart(IServiceRadioCallBack cb, Radio radio)
				throws RemoteException {
			// TODO Auto-generated method stub
			
		}


		/*
		@Override
		public void doStart(IServiceRadioCallBack cb, String url,
				String trigramme, String nom) throws RemoteException {
			// TODO Auto-generated method stub
			
		}*/
	}; 
	
	@Override
	public IBinder onBind(Intent arg0) {
		Toast.makeText(mContext, "onBind called by "
			  + Thread.currentThread().getName(), Toast.LENGTH_LONG).show();
		mHandler.sendEmptyMessage(TIMER_TASK);
		return mMyBindService;
	}

	@Override
	public boolean onUnbind(Intent intent) {
		Toast.makeText(mContext, "onUnbind called by "
			  + Thread.currentThread().getName(), Toast.LENGTH_LONG).show();
		return true;
	}
	
	
 
	/**
     * Returns the contained StatefulMediaPlayer
     * @return
     */
    public StatefulMediaPlayer getMediaPlayer() {
        return mMediaPlayer;
    }

    
    /**
     * Initializes a StatefulMediaPlayer for streaming playback of the provided StreamStation
     * @param station The StreamStation representing the station to play
     */
    public void initializePlayer(StreamStation station) {
        //mClient.onInitializePlayerStart("Connecting...");
        mMediaPlayer = new StatefulMediaPlayer(station);
        mMediaPlayer.setOnBufferingUpdateListener(this);
        mMediaPlayer.setOnInfoListener(this);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.prepareAsync();
    }
    
    /**
     * Initializes a StatefulMediaPlayer for streaming playback of the provided stream url
     * @param streamUrl The URL of the stream to play.
     */
    public void initializePlayer(String streamUrl) {
    	if(streamUrl!=null){
    		mMediaPlayer = new StatefulMediaPlayer();
    		mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    		try {
    			mMediaPlayer.setDataSource(streamUrl);
    		}
    		catch (Exception e) {
    			Log.e("MediaPlayerService", "error setting data source");
    			mMediaPlayer.setState(MPStates.ERROR);
    		}
    		mMediaPlayer.setOnBufferingUpdateListener(this);
    		mMediaPlayer.setOnInfoListener(this);
    		mMediaPlayer.setOnPreparedListener(this);
    		mMediaPlayer.prepareAsync();
    	}
    }

    
    
	@Override
	public void onCreate() {
		mContext = this;
		mHandler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				Bundle bundle = msg.getData();
				String streamUrl = bundle.getString("params");
				Log.i(TAG, "startMedia  "+bundle.toString() );
				Log.i(TAG, "startMedia  "+streamUrl );
				switch(msg.what){
				case START_MEDIA_PLAYER :
					Log.i(TAG, "START_MEDIA_PLAYER  ssdsds "+streamUrl);
					//resetMediaPlaer();
					if(streamUrl!=null){
						//stopMediaPlayer();
						initializePlayer(streamUrl);
						startMediaPlayer();
					}
								
				break;
				case STOP_MEDIA_PLAYER:
					int observerNum = mObservers.beginBroadcast();
					for(int i = 0; i < observerNum; i++){
						try {
							mObservers.getBroadcastItem(i).streamingReady();
						} catch (RemoteException e) {
						}
					}
					mObservers.finishBroadcast();
					sendEmptyMessageDelayed(TIMER_TASK, DELAY);
					break;
				}
			}
			
		};
		mlistRadio =App.getConf();
		Toast.makeText(mContext, "onCreate called by " + Thread.currentThread().getName(), Toast.LENGTH_LONG).show();
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		Toast.makeText(mContext, "onDestroy called by " + Thread.currentThread().getName(), Toast.LENGTH_LONG).show();
		super.onDestroy();
	}

	@Override
	public void onRebind(Intent intent) {
		Toast.makeText(mContext, "onRebind called by " + Thread.currentThread().getName(), Toast.LENGTH_LONG).show();
		super.onRebind(intent);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
	Log.i(TAG, "onStartCommand");
	//initializePlayer("http://195.154.107.81:8000/radiob?1393948161681.mp3");
	//startMediaPlayer();
	return super.onStartCommand(intent, flags, startId);
	}
	
	
	 


	@Override
	public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
		mMediaPlayer.reset();
        mClient.onError();
        return true;
	}

	@Override
	public void onPrepared(MediaPlayer arg0) {
		// TODO Auto-generated method stub
		// mClient.onInitializePlayerSuccess();
	     startMediaPlayer();
	}

	
	/**
     * Pauses the contained StatefulMediaPlayer
     */
    public void pauseMediaPlayer() {
        Log.d("MediaPlayerService","pauseMediaPlayer() called");
        mMediaPlayer.pause();
        stopForeground(true);
 
    }
    
    /**
     * Sets the client using this service.
     * @param client The client of this service, which implements the IMediaPlayerServiceClient interface
     */
    public void setClient(IMediaPlayerServiceClient client) {
        this.mClient = client;
    }
 
     /**
     * Starts the contained StatefulMediaPlayer and foregrounds the service to support
     * persisted background playback.
     */
    public void startMediaPlayer() {
        Context context = getApplicationContext();
 
        //set to foreground
        Notification notification = new Notification(android.R.drawable.ic_media_play, "MediaPlayerService",
                System.currentTimeMillis());
        Intent notificationIntent = new Intent(this, Home.class);
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
 
        CharSequence contentTitle = "MediaPlayerService Is Playing";
        //CharSequence contentText = mMediaPlayer.getStreamStation().getStationLabel();
        //notification.setLatestEventInfo(context, contentTitle,
         //       contentText, pendingIntent);
        //startForeground(1, notification);
 
        Log.d("MediaPlayerService","startMediaPlayer() called");
        mMediaPlayer.start();
    }
 
    /**
     * Stops the contained StatefulMediaPlayer.
     */
    public void stopMediaPlayer() {
        stopForeground(true);
        mMediaPlayer.stop();
        mMediaPlayer.release();
    }
 
    public void resetMediaPlaer() {
        stopForeground(true);
        mMediaPlayer.reset();
    }
    
    
	@Override
	public boolean onInfo(MediaPlayer arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub
		 return false;
	}

	@Override
	public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}
}